package com.mantru.iotpot.Cook;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cleaning.CleanWayActivity;
import com.mantru.iotpot.Cook.adapter.CookStepRecyclerViewAdapter;
import com.mantru.iotpot.DateClass.CookStep;
import com.mantru.iotpot.DateClass.FoodList;
import com.mantru.iotpot.Home.HomeActivity;
import com.mantru.iotpot.Tools.ImageLoader;
import com.mantru.iotpot.R;
import com.mantru.iotpot.DateClass.ingredients;
import com.mantru.iotpot.Tools.LoadingDialogUtil;
import com.mantru.iotpot.Tools.tools;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.EventMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CookActivity extends AppCompatActivity implements View.OnClickListener {
    private ApplicationClass ac;
    private Handler handler; // 用于定时任务
    private int sid;
    private int vegetableId;
    private FoodList vegetableList = new FoodList("","","");
    private List<CookStep> Step = new ArrayList<>();
    private TextView foodname;
    private ImageView foodimg;
    private TextView num;
    private TextView cook_time;
    private TextView cook_speed;
    private TextView wendu;
    private TextView cook_steep;
    private ingredients ingredient = new ingredients("","","","","");
    private int steep;// 炒菜状态： 0未执行、1炒制中、2已完成、3终止了
    private long time;
    private int temp;
    private int speed;
    private int gear_num;
    private AlertDialog dialog; // 用于存储弹窗对象
    private Runnable runnable; // 用于计时器逻辑
    private Button finishbut;
    private boolean result;
    private int pan = 0;
    private Button finishbut2;
    private RecyclerView recyclerView;
    private CookStepRecyclerViewAdapter adapter;
    private String quantity = "";
    private CountDownTimer timer;
    private LinearLayout st;
    private View lock;
    private TextView gear;
    private LinearLayout wendu_box1;
    private LinearLayout wendu_box2;
    private Dialog dialog1;
    private int ErrorGripper = 0;//0表示机械臂没有故障，1表示机械臂出现故障
    private String TAG = "CookActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cook);
        // 接收传递的数据
        sid = Integer.parseInt(getIntent().getStringExtra("sid"));
        vegetableId = Integer.parseInt(getIntent().getStringExtra("vegetableId"));
        quantity = getIntent().getStringExtra("quantity");
        Log.d("num","sid: " + sid + " vegetableId: " + vegetableId);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        ac.GetSQLData_Vegetable_Entity(vegetableId);
        result = ac.Cooking_Start(vegetableId, sid);
        EventBus.getDefault().register(this);

        // 初始化 UI 控件
        foodname = findViewById(R.id.cook_name);
        foodimg = findViewById(R.id.cook_food_img);
        num = findViewById(R.id.cook_num);
        cook_time = findViewById(R.id.cook_food_time);
        cook_speed = findViewById(R.id.cook_food_speed);
        gear = findViewById(R.id.cook_food_gear);
        wendu = findViewById(R.id.cook_food_wendu);
        cook_steep = findViewById(R.id.cook_food_text1);
        finishbut = findViewById(R.id.cook_finish);
        finishbut2 = findViewById(R.id.cook_finish2);
        lock = findViewById(R.id.overlay);
        st = findViewById(R.id.cook_step);
        wendu_box1 = findViewById(R.id.cook_food_wendu_box1);
        wendu_box2 = findViewById(R.id.cook_food_wendu_box2);
        st.setOnClickListener(this);
        finishbut.setOnClickListener(this);
        finishbut2.setOnClickListener(this);
        findViewById(R.id.cook_back).setOnClickListener(this);

        analysis();//解析菜品信息
        // 调用 cheak 方法
        cheak();
        Log.d("num","num: 3");
        ImageLoader.loadImage(vegetableList.getFaceImageUrl(),foodimg);
        foodname.setText(vegetableList.getVegetableName());
        num.setText(quantity + "份");
        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CookStepRecyclerViewAdapter(Step);
        recyclerView.setAdapter(adapter);
        handler = new Handler();// 初始化 Handler
        startcheak();
    }

    public void cheak() { // 更新状态
        Log.d("num", "result: " + result);
        if (result) {
            // 0未执行、1炒制中、2已完成、3终止了
            steep = ac.jobmaster.steep_status;
            Log.d("cheak", "s :" + steep);
            // 剩余时间
            time = ac.jobmaster.remain_time;
            Log.d("cheak", "time :" + time);
            // 0-5档，0表示停止
            speed = ac.gripper_speed_value_read;
            Log.d("cheak", "speed :" + speed);
            //当前挡位
            gear_num = ac.realtime_fire_value;
            Log.d("cheak","gear_num: " + gear_num);
            // 锅温度
            temp = ac.pot_temperature_value;
            Log.d("cheak", "temp :" + temp);
            String json = ac.jobmaster.getJsonString();
            Log.d("数据", "jsonObject:" + json);
            // 清空 Step 列表
            Step.clear();
            try {
                // 将 JSON 字符串解析为 JSONObject
                JSONObject jsonObject = new JSONObject(json);
                Log.d("COOKStep", "jsonObject: " + jsonObject);
                // 获取 data 数组
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                Log.d("数据", "开始解析:");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    String steep_index = item.getString("steep_index");
                    String steep_name = item.getString("steep_name");
                    String steep_status = item.getString("steep_status");
                    String remain_time = item.getString("remain_time");
                    // 将数据添加到 Step 列表
                    Step.add(new CookStep(steep_index, steep_name, steep_status, remain_time));
                    Log.d("Step", "steep_index: " + steep_index + " steep_name: " + steep_name + " steep_status: "
                            + steep_status + " remain_time: " + remain_time);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("数据", "JSON 解析失败: " + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("数据", "其他错误: " + e.getMessage());
            }

            // 确保 adapter 不为 null
            if (adapter != null) {
                change();
                adapter.notifyDataSetChanged();
                scrollToLatestActiveStep();
            } else {
                Log.e("CookActivity", "Adapter is null, cannot notify data set changed");
            }

            // 如果 steep == 0，显示弹窗
            if (steep == 0) {
                showDialog();
            } else if (steep == 2){//已完成
                finishbut.setVisibility(View.GONE);
                finishbut2.setVisibility(View.VISIBLE);
                lock.setVisibility(View.GONE);
            } else if (steep == 1){
                // 如果 steep 不为 0，关闭弹窗
                dismissDialog();
            }
        } else {
            //Toast.makeText(this, "发生错误", Toast.LENGTH_SHORT).show();
            ToastUtils.show(this, "发生错误");
        }
    }

    public void analysis(){
        String json_data = ac.GetSQLData_Vegetable_Entity(vegetableId);//获取菜单详情
        try {
            JSONObject jsonObject = new JSONObject(json_data);
            JSONObject dataObject = jsonObject.getJSONObject("data");
            Log.d("num","dataObject: " + dataObject);
            String vegetableId = dataObject.getString("vegetable_id");
            String vegetableName = dataObject.getString("vegetable_name");
            String faceImageUrl = dataObject.getString("face_image_url");
            faceImageUrl = faceImageUrl.replace("file:///", "");
            vegetableList.setVegetableId(vegetableId);
            vegetableList.setVegetableName(vegetableName);
            vegetableList.setFaceImageUrl(faceImageUrl);
        }catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void startcheak(){//定时任务
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                cheak();
                // 每隔1秒重复执行
                handler.postDelayed(this, 1000);
            }
        }, 1000);
    }

    @Override
    protected void onDestroy() {
        dismissDialog(); // 清理弹窗和定时器
        if (handler != null) {
            handler.removeCallbacksAndMessages(null); // 移除所有 Handler 任务
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (dialog1 != null && dialog1.isShowing()) {
            dialog1.dismiss();
            dialog1 = null;
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void change(){//更改显示
        // 确保在 UI 线程中更新
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cook_time.setText(String.valueOf(time));
                cook_speed.setText(String.valueOf(speed));
                gear.setText(String.valueOf(gear_num));
                if (ac.pot_temperature_is_error == true){
                    wendu_box1.setVisibility(View.GONE);
                    wendu_box2.setVisibility(View.VISIBLE);
                }else {
                    wendu_box2.setVisibility(View.GONE);
                    wendu_box1.setVisibility(View.VISIBLE);
                    wendu.setText(String.valueOf(temp));
                }
                if (steep == 0){
                    cook_steep.setText("未执行");
                } else if (steep == 1) {
                    cook_steep.setText("炒制中");
                }else if (steep == 2) {
                    cook_steep.setText("已完成");
                    finishbut.setText("出菜");
                }else if (steep == 3) {
                    cook_steep.setText("已终止");
                    finishbut.setText("出菜");
                }
                Log.d("CookActivity", "UI updated.");
            }
        });
    }

    // 显示弹窗
    private void showDialog() {
        // 如果弹窗已经显示，则不重复显示
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.waitcook, null);
        builder.setView(dialogView);

        // 获取弹窗中的按钮和计时器文本
        final TextView countdownTextView = dialogView.findViewById(R.id.countdownTextView);

        timer = new CountDownTimer(60 * 1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTextView.setText(Integer.parseInt(String.valueOf(millisUntilFinished / 1000)) + "S");
            }

            @Override
            public void onFinish() {
                // 如果弹窗存在且正在显示，则关闭它
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if ( timer != null ){
                    timer.cancel();
                    timer = null;
                }
                finish();
                //Toast.makeText(CookActivity.this,"设备就位失败，请重试！",Toast.LENGTH_SHORT).show();
                ToastUtils.show(CookActivity.this,"设备就位失败，请重试！");
                ac.Cooking_Stop();
            }
        };
        timer.start();

        // 创建并显示弹窗
        dialog = builder.create();
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);

        // 保存计时器和弹窗引用，以便在状态改变时停止计时器和关闭弹窗
        this.dialog = dialog;
        this.handler = handler;
        this.runnable = runnable;
    }

    // 关闭弹窗
    private void dismissDialog() {
        // 如果弹窗存在且正在显示，则关闭它
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
                if ( timer != null ){
                    timer.cancel();
                    timer = null;
                }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.cook_finish){//点击终止
            String title = "提示";
            String content = "确认要终止炒菜吗？";
            if (ac.box_position_value <=4 && ac.box_throw_move != 1){
                tools.showCustomDialog(this, title, content, new tools.OnDialogButtonClickListener() {
                    @Override
                    public void onConfirmClick() {
                        // 点击确认按钮后的逻辑
//                    Toast.makeText(CookActivity.this, "确认", Toast.LENGTH_SHORT).show();
                        ac.Cooking_Stop();
                        finishbut.setVisibility(View.GONE);
                        finishbut2.setVisibility(View.VISIBLE);
                        lock.setVisibility(View.GONE);
                    }
                    @Override
                    public void onCancelClick() {
                        // 点击取消按钮后的逻辑
//                    Toast.makeText(CookActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }else {
                ToastUtils.show(this, "料盒仍在运动中，请等待");
            }
        } else if (v.getId() == R.id.cook_back) {
            ac.SaveLog("自动炒菜点击返回时steep的值为：" + steep);// 炒菜状态： 0未执行、1炒制中、2已完成、3终止了
            if (steep == 1 || steep == 2){//在炒制中点击返回
                String title = "提示";
                String content = "";
                if (steep == 1){
                    content = "确认要终止炒菜吗？";
                } else if (steep == 2) {
                    content = "当前还没有出菜，请问是否要退出？";
                }
                tools.showCustomDialog(this, title, content, new tools.OnDialogButtonClickListener() {
                    @Override
                    public void onConfirmClick() {
                        // 点击确认按钮后的逻辑
                        //Toast.makeText(CookActivity.this, "确认", Toast.LENGTH_SHORT).show();
//                        ToastUtils.show(CookActivity.this, "确认");
                        ac.Cooking_Stop_Quickly();
                        LoadingDialogUtil.showLoadingDialog(CookActivity.this);
                        finish();
                    }

                    @Override
                    public void onCancelClick() {
                        // 点击取消按钮后的逻辑
                        //Toast.makeText(CookActivity.this, "取消", Toast.LENGTH_SHORT).show();
                        ToastUtils.show(CookActivity.this, "取消");
                    }
                });
            }else {
                ac.Cooking_Stop_Quickly();
                LoadingDialogUtil.showLoadingDialog(CookActivity.this);
                finish();
            }
        } else if (v.getId() == R.id.cook_finish2) {//点击出菜按钮
            String str = ac.CheckIsCanMove("出菜");
            if (str.length() > 0){
                //Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
                ToastUtils.show(this,str);
                return;
            }
            boolean result = ac.Cooking_PourOut();
            ac.SaveLog("已经发送出菜指令，结果为： " + result);
            if (result){
                if (ErrorGripper == 0){
//                    LoadingDialogUtil.showLoadingDialog(CookActivity.this);
                    startActivity(new Intent(this, PutFoodActivity.class));
                    finish();
                } else if (ErrorGripper == 1) {//机械臂出现异常
                    ShowCheakDialog();
                }
            }else {
                ToastUtils.show(this,"出菜错误");
            }

        } else if (v.getId() == R.id.cook_step) {
//            Toast.makeText(this,"此功能还在开发中",Toast.LENGTH_SHORT).show();
//            LoadingDialogUtil.showLoadingDialog(CookActivity.this);
            startActivity(new Intent(this,StepDiagramActivity.class));
        }
    }

    // 新增方法：滚动到最新的进行中的步骤
    private void scrollToLatestActiveStep() {
        // 找到第一个状态为 "1"（进行中）的步骤
        for (int i = 0; i < Step.size(); i++) {
            if (Step.get(i).getSteep_status().equals("1")) {
                // 使用 smoothScrollToPosition 平滑滚动到该位置
                recyclerView.smoothScrollToPosition(i);
                return;
            }
        }

        // 如果没有进行中的步骤，滚动到最后一个位置
        if (!Step.isEmpty()) {
            recyclerView.smoothScrollToPosition(Step.size() - 1);
        }
    }

//    private BroadcastReceiver receiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if ("ACTION_CLOSE_LOADING_DIALOG".equals(intent.getAction())) {
//                LoadingDialogUtil.closeLoadingDialog();
//            }
//        }
//    };

    @Override
    protected void onStart() {
        super.onStart();
//        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("ACTION_CLOSE_LOADING_DIALOG"));
    }

    @Override
    protected void onStop() {
        super.onStop();
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        // 在界面渲染完成后发送广播关闭弹窗
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                ((ApplicationClass) getApplication()).sendBroadcast("ACTION_CLOSE_LOADING_DIALOG");
//            }
//        });
    }

    private void ShowCheakDialog(){
        // 如果弹窗已经显示，则不重复显示
        if (dialog1 != null && dialog1.isShowing()) {
            return;
        }
        // 创建自定义对话框
        dialog1 = new Dialog(this);
        dialog1.setContentView(R.layout.manual_cheak_dialog); // 设置对话框的布局

        Button stop = dialog1.findViewById(R.id.manual_cheak_dialog_stop);
        Button low = dialog1.findViewById(R.id.manual_cheak_dialog_low);
        Button rotate = dialog1.findViewById(R.id.manual_cheak_dialog_rotate);

        stop.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Stop();
            ac.SaveLog("用户点击了炒菜爪手动寻位的停止按钮");
        });

        low.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_Slow();
            ac.SaveLog("用户点击了炒菜爪手动寻位的低速按钮");
        });

        rotate.setOnClickListener(v -> {
            ac.Device_SendCommand_Gripper_OK();
            ac.SaveLog("用户点击了炒菜爪手动寻位的确认按钮");
            dialog1.dismiss();
            LoadingDialogUtil.showLoadingDialog(CookActivity.this);
            startActivity(new Intent(this, PutFoodActivity.class));
            finish();
        });
        // 关键代码：设置窗口背景透明
        if (dialog1.getWindow() != null) {
            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        dialog1.setCanceledOnTouchOutside(false);

        // 显示对话框
        dialog1.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event){
        if (event.id == EventMessage.MSG_ID_ErrorGripper){//收到了机械臂出现故障的消息
            ErrorGripper = 1;
            ac.SaveLog(TAG + " 界面接收到机械臂出现故障的事件");
        }
    }
}